package com.friddle.Download.Selumin;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.openqa.selenium.Cookie;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

import com.friddle.Download.PageGet.GetConfigure;
import com.friddle.Download.PageGet.PageResult;
import com.friddle.ocr.UUOcr.UUOcr;

/**
 * Created by friddle on 15/4/7.
 */
public class SeleniumGridDownload {
	RemoteWebDriver driver;

	public SeleniumGridDownload(String url, String browseName) {
		try {
			DesiredCapabilities dr = DesiredCapabilities.chrome();
			dr.setBrowserName(browseName);
			driver = new RemoteWebDriver(new URL(url), dr);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}

	public synchronized PageResult getPageContent(String url, GetConfigure configure) {
		if (configure == null)
			configure = new GetConfigure();
		Map<String, String> cookiesmap = configure.getCookies();
		Iterator<String> cookies = cookiesmap.keySet().iterator();
		while (cookies.hasNext()) {
			String key = cookies.next();
			driver.manage().addCookie(new Cookie(key, cookiesmap.get(key)));
		}
		driver.navigate().to(url);
		System.out.println(driver.getPageSource());
		PageResult mResult = new PageResult();
		mResult.setSuccess(true);
		mResult.setHtmlContent(driver.getPageSource());
		return mResult;
	}

	public static void main(String[] args) {
		SeleniumGridDownload download = new SeleniumGridDownload("http://192.168.59.103:4444/wd/hub", "chrome");
		download.testTaobao();
	}

	public void testTaobao() {
		driver.navigate().to("https://login.taobao.com");
		driver.findElementByXPath("//input[@id=\"TPL_username_1\"]").sendKeys("friddle@qq.com");
		driver.findElementByXPath("//input[@id=\"TPL_password_1\"]").sendKeys("lyd88636311");
		String captch = driver.findElementByXPath("//img[@id=\"J_StandardCode_m\"]").getAttribute("src");
		if (!captch.contains("blank")) {
			UUOcr ocr = UUOcr.getOcrInstance();
			Map<String, String> values = new HashMap<>();
			values.put("username", "friddle");
			values.put("password", "friddle88636311");
			ocr.initEnviroment(values);
			String captch_value = ocr.parseUrls(captch, "1004").getValue();
			driver.findElementByXPath("//input[@id=\"J_CodeInput_i\"]").sendKeys(captch_value);
		}
		driver.findElementByXPath("//button[@id=\"J_SubmitStatic\"]").click();
		System.out.print(driver.getTitle());
		System.out.print(driver.manage().getCookies().toArray());
		driver.close();
	}

}
